using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XFGameFramework;
using XFABManager;
using XFGameFramework.ScriptableObjectSystem;
using UnityEngine.SceneManagement;
public class LevelsController : Controller
{
    private TimeController timeController => Module.LoadController<TimeController>();
    public LevelsConfigData GetLevelInfo(int levelId)
    {
        // 查询配表
        ScriptableObjectConfigs configs = ScriptableObjectManager.GetConfig("LevelsConfig");
        LevelsConfigData levelsConfigData = configs.GetScriptableObjectData(levelId) as LevelsConfigData;
        return levelsConfigData;
    }
    public void EnterLevel()
    {
        Debug.Log((int)timeController.CurrentPeriod);
        LevelsConfigData levelsConfigData = GetLevelInfo((int)timeController.CurrentPeriod);

        if (levelsConfigData == null) throw new System.Exception("Level not found");

        CoroutineStarter.Start(Loading(levelsConfigData.sceneName));
    }
    private IEnumerator Loading(string sceneName)
    {
        //加载场景
        bool finish = false;

        LoadingPanel loadingPanel = Module.LoadPanel<LoadingPanel>(UIType.DontDestroyUI);//加载loadingPanel,因为跨越两个场景，是不能销毁的UI

        Module.LoadController<SceneController>().LoadScene(sceneName, () =>
        {
            finish = true;
        }, (p) =>
        {
            loadingPanel.UpdateProgress(p);
        });

        while (!finish || loadingPanel != null && !loadingPanel.isDone())
        {
            yield return null;
        }
        //关闭加载中的场景
        if (loadingPanel != null)
        {
            loadingPanel.Close();
            loadingPanel = null;
        }

        OnLevelLoaded();
    }

    public void OnLevelLoaded()
    {
        Scene scene = SceneManager.GetActiveScene();
        // 加载角色
        Turtle turtle = Module.LoadView<Turtle>();
        GameObject pos = scene.FindRootGameObject("PlayerPos");
        if (pos == null)throw new System.Exception("PlayerPos not found");
        turtle.transform.position = pos.transform.position;

        
        GameObject BackgroundPos = scene.FindRootGameObject("Background");

        // Bottom bottom = Module.LoadView<Bottom>();

        // Window window = Module.LoadView<Window>();

        // Hight hight = Module.LoadView<Hight>();
        
        Apple apple = Module.LoadView<Apple>();

    }
}
